package com.rc.saas.tenant.interceptor.parser;

import com.rc.saas.tenant.mapper.tenant.TenantMapper;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Created by sven on 2019/4/29
 */
@Component
public class SqlParserHandler {
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private SelectParser selectParser;

    /**
     * 将SQL添加租户条件
     * @param sql
     * @param getTenantCode
     * @return
     */
    public String parseSql(String sql, String getTenantCode) {
        String newSql = null;
        // sql字符串转换成对象形式
        Statement stmt;
        try {
            stmt = CCJSqlParserUtil.parse(sql);

            // 针对不同类型的SQL 做出不同处理
            if (stmt instanceof Insert) {
                //newSql = getInsertProcess().addWhere((Insert) stmt);
            } else if (stmt instanceof Delete) {
                //newSql = getDeleteProcess().addWhere((Delete) stmt);
            } else if (stmt instanceof Update) {
                //newSql = getUpdateProcess().addWhere((Update) stmt);
            } else if (stmt instanceof Select) {
                newSql = selectParser.addWhere((Select) stmt);
            } else if (stmt instanceof CreateTable) {
                //newSql = getCreateProcess().addWhere(stmt);
            }

        } catch (Exception e) {
            throw new RuntimeException("SQL转换失败:" + sql + "\r\n" + Arrays.toString(e.getStackTrace()));
        }

        return newSql;
    }
}
